package cn.hgpu.servlet;

import cn.hgpu.mapper.RoleMapper;
import cn.hgpu.pojo.Role;
import cn.hgpu.utils.MybatisUtils;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/role/edit")
public class RoleEditServlet extends HttpServlet {
    private RoleMapper roleMapper = MybatisUtils.getMapper(RoleMapper.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String roleName = req.getParameter("roleName");

        if(StringUtils.isNullOrEmpty(roleName)){
            req.setAttribute("msg","角色名称不能为空！");
            //转发
            req.getRequestDispatcher("/role/edit.jsp").forward(req,resp);
            return;
        }
        //2.不能重复
        Role role = roleMapper.selectByRoleName(roleName);
        if(role!=null&&Integer.parseInt(id)!=role.getId()){
            req.setAttribute("msg","角色不能重复！");
            //转发
            req.getRequestDispatcher("/role/edit.jsp").forward(req,resp);
            return;
        }
        roleMapper.update(Integer.parseInt(id),roleName);

        // 跳转页面
        resp.sendRedirect("/role/list");
    }
}
